import threading
from typing import Dict, List, Optional

import psutil
from pydantic import BaseModel
import datetime

class NIC(BaseModel):
    """网络接口卡信息模型"""
    nic_name: str = None  # 网络接口名称，如eth0、wlan0
    nic_timestamp: datetime.datetime = datetime.datetime.now()  # 数据采集时间戳
    nic_address: Dict[str, List] = {}  # 接口IP地址，格式: {family: [addresses]}
    nic_netmask: Dict[str, List] = {}  # 子网掩码，格式: {family: [netmasks]}
    nic_broadcast: Dict[str, List] = {}  # 广播地址，格式: {family: [broadcasts]}
    nic_ptp: Dict[str, List] = {}  # 点对点连接地址，格式: {family: [ptp_addresses]}
    nic_is_up: bool = None  # 接口是否处于激活状态
    nic_duplex: str = None  # 双工模式，如full、half
    nic_speed: int = 0  # 网络带宽，单位为Mbps
    nic_mtu: int = None  # 最大传输单元大小



class NetworkInterface(BaseModel):
    name: str
    ip: str
    netmask: str

class NetworkInfo(BaseModel):
    bytes_sent: float
    bytes_recv: float
    packets_sent: int
    packets_recv: int
    speed_kb: float
    interfaces: List[NetworkInterface]


class Disk(BaseModel):
    """磁盘使用情况模型"""
    disk_timestamp: int = 0  # 数据采集时间戳(整数形式)
    disk_time: datetime.datetime = datetime.datetime.now()  # 数据采集时间
    disk_total: int = 0  # 磁盘总容量，单位为字节
    disk_used: int = 0  # 已使用磁盘空间，单位为字节
    disk_free: int = 0  # 空闲磁盘空间，单位为字节
    disk_percentage_usage: int = 0  # 磁盘使用率百分比
    disk_read_count: int = 0  # 磁盘读取操作次数
    disk_write_count: int = 0  # 磁盘写入操作次数
    disk_read_bytes: int = 0  # 磁盘读取字节数
    disk_write_bytes: int = 0  # 磁盘写入字节数




class DiskPartition(BaseModel):
    device: str
    mountpoint: str
    fstype: str
    total: float
    used: float
    free: float
    percent: float
    read_speed: float = 0
    write_speed: float = 0



class DiskInfo(BaseModel):
    total: float
    used: float
    free: float
    percent: float
    partitions: List[DiskPartition]
    system_read_bytes: int = 0
    system_write_bytes: int = 0
    system_read_speed: float = 0
    system_write_speed: float = 0

class SwapMemory(BaseModel):
    """交换空间(虚拟内存)使用情况模型"""
    sm_total: int = None  # 交换空间总大小，单位为字节
    sm_used: int = None  # 已使用交换空间，单位为字节
    sm_free: int = None  # 空闲交换空间，单位为字节
    sm_percent: int = None  # 交换空间使用率百分比
    sm_in: int = None  # 从磁盘交换到内存的字节数
    sm_out: int = None  # 从内存交换到磁盘的字节数
    sm_timestamp: datetime.datetime = datetime.datetime.now()  # 数据采集时间

class Connection(BaseModel):
    """网络连接信息模型"""
    CXN_fd: int = None  # 文件描述符
    CXN_family: str = None  # 地址族，如AF_INET、AF_INET6
    CXN_type: str = None  # 连接类型，如SOCK_STREAM、SOCK_DGRAM
    CXN_TCP_status: str = None  # TCP连接状态，如ESTABLISHED、LISTEN
    CXN_pid: int = None  # 关联的进程ID

class CPU_Logical(BaseModel):
    """逻辑CPU核心信息模型"""
    cpu_logical_id: int = None  # 逻辑CPU ID
    cpu_timestamp: datetime.datetime = None  # 数据采集时间
    cpu_percent: float = None  # CPU使用率百分比
    cpu_freq: float = None  # CPU频率，单位为GHz
    cpu_time_user: float = None  # 用户模式下的CPU时间
    cpu_time_system: float = None  # 系统模式下的CPU时间
    cpu_time_idle: float = None  # 空闲状态下的CPU时间
    cpu_time_IOWait: float = None  # 等待I/O完成的CPU时间
    cpu_time_irq: float = None  # 处理硬件中断的CPU时间
    cpu_time_softIrq: float = None  # 处理软件中断的CPU时间
    cpu_time_steal: float = None  # 被其他虚拟机偷走的CPU时间
    cpu_time_guest: float = None  # 运行虚拟机的CPU时间
    cpu_time_guest_nice: float = None  # 运行低优先级虚拟机的CPU时间
    cpu_time_nice: float = None  # 运行低优先级进程的CPU时间
    cpu_time_dpc: float = None  # 处理延迟过程调用的CPU时间

class CPU_Entity(BaseModel):
    """CPU整体信息模型"""
    cpu_entity_id: int = None  # CPU实体ID
    cpu_count: int = None  # CPU物理核心数
    cpu_totoal_percent: float = None
    cpu_loadavg_1m: float = None  # 1分钟系统平均负载
    cpu_loadavg_5m: float = None  # 5分钟系统平均负载
    cpu_loadavg_15m: float = None  # 15分钟系统平均负载
    logicalCPUs: List[CPU_Logical] = []  # 逻辑CPU核心列表

class VirtualMemoryInfo(BaseModel):
    """物理内存使用情况模型"""
    vm_total: float = None  # 总物理内存，单位为字节
    vm_percent:float
    vm_available: float = None  # 可用物理内存，单位为字节
    vm_used: float = None  # 已使用物理内存，单位为字节
    vm_free: float = None  # 空闲物理内存，单位为字节
    vm_active: float = None  # 活跃内存，单位为字节
    vm_inactive: float = None  # 非活跃内存，单位为字节
    vm_buffers: float = None  # 缓冲区内存，单位为字节
    vm_cached: float = None  # 缓存内存，单位为字节
    vm_shared: float = None  # 共享内存，单位为字节
    vm_slab: float = None  # 内核数据结构缓存，单位为字节
    vm_timestamp: datetime.datetime = datetime.datetime.now()  # 数据采集时间

class Process(BaseModel):
    """进程信息模型"""
    process_pid: int = None  # 进程ID
    process_ppid: int = None  # 父进程ID
    process_name: str = None  # 进程名称
    process_nice: int = None  # 进程优先级(nice值)
    time_stamp: datetime.datetime = None  # 数据采集时间
    process_create_time: datetime.datetime = None  # 进程创建时间
    process_status: str = None  # 进程状态，如running、sleeping
    process_RLIMIT_AS: tuple = None  # 进程地址空间限制
    process_RLIMIT_CORE: tuple = None  # 核心文件大小限制
    process_RLIMIT_CPU: tuple = None  # CPU时间限制
    process_RLIMIT_DATA: tuple = None  # 数据段大小限制
    process_RLIMIT_FSIZE: tuple = None  # 文件大小限制
    process_RLIMIT_LOCKS: tuple = None  # 文件锁数量限制
    process_RLIMIT_MEMLOCK: tuple = None  # 锁定内存限制
    process_RLIMIT_NOFILE: tuple = None  # 文件描述符数量限制
    process_RLIMIT_NPROC: tuple = None  # 进程数量限制
    process_RLIMIT_RSS: tuple = None  # 驻留集大小限制
    process_RLIMIT_STACK: tuple = None  # 栈大小限制
    process_io_read_count_speed: float = None  # 磁盘读取速率(次数/秒)
    process_io_write_count_speed: float = None  # 磁盘写入速率(次数/秒)
    process_io_read_bytes_speed: float = None  # 磁盘读取速率(字节/秒)
    process_io_write_bytes_speed: float = None  # 磁盘写入速率(字节/秒)
    process_ionice: int = None  # I/O调度优先级
    process_io_read_count: int = None  # 总磁盘读取次数
    process_io_write_count: int = None  # 总磁盘写入次数
    process_io_read_bytes: int = None  # 总磁盘读取字节数
    process_io_write_bytes: int = None  # 总磁盘写入字节数
    process_io_read_chars: int = None  # 读取的字符数
    process_io_write_chars: int = None  # 写入的字符数
    process_num_ctx_switches: int = None  # 上下文切换次数
    process_num_fds: int = None  # 打开的文件描述符数量
    process_num_threads: int = None  # 线程数量
    process_cpu_percent: float = None  # CPU使用率百分比
    process_cpu_affinity: List[int] = None  # CPU亲和性设置
    process_cpu_num: int = None  # 当前运行的CPU核心
    process_memory_rss: int = None  # 驻留集大小，单位为字节
    process_memory_vms: int = None  # 虚拟内存大小，单位为字节
    process_memory_dirty: int = None  # 脏页数量，单位为字节
    process_memory_percent: float = None  # 内存使用率百分比
    process_connections: List = []  # 进程的网络连接列表
    process_is_running: bool = None  # 进程是否正在运行

class EyeOnClient(BaseModel):
    """客户端系统监控信息汇总模型"""
    server_id: str = None  # 服务器唯一标识符
    CPU_Entity: CPU_Entity  # CPU信息
    VM: VirtualMemoryInfo  # 内存信息
    swapMemory: SwapMemory  # 交换空间信息
    Disk: Disk  # 磁盘信息
    network_interfaces: List[NIC] = []  # 网络接口列表
    connections: List[Connection] = []  # 网络连接列表
    processes: List[Process] = []  # 进程列表
    timestamp: datetime.datetime = None  # 数据采集时间戳

class ProcessInfo(BaseModel):
    """进程信息数据模型"""
    pid: int
    ppid: int
    name: str
    exePath: str
    status: str
    user: Optional[str]
    cpuPercent: float
    memoryPercent: float
    memoryUsage: int
    startTime: str
    runTime: str
    threads: int
    commandLine: str
    nice: int
    port: List[int] = []
# class memery_history(BaseModel):
#     """内存历史数据模型"""
#     cpu_history = []
#     memory_history = []
#     disk_history = []
#     network_history = []
#     max_history = 60  # 保存最近60个数据点
#     last_network_io = None
#     boot_time = []
#     _lock = threading.Lock()
#     _monitor_task = None